package com.chuangke.fss.disk;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.chuangke.common.exception.ChuangkeException;
import com.chuangke.common.utils.DateUtils;
import com.chuangke.common.utils.FileUtils;
import com.chuangke.file.model.FileBrief;
import com.chuangke.file.model.FileChunk;
import com.chuangke.fss.FSS;
import com.chuangke.fss.FSSConfig;
import com.chuangke.fss.model.FSSObject;
import com.chuangke.fss.model.StorageType;

@Component
public class FSSDisk implements FSS {

	@Autowired
	private FSSConfig fssConfig;

	private String getFullFilePath(String suffix) {
		Date date = new Date();
		String dateDir = DateUtils.getDate(date, "yyyy") + File.separator + DateUtils.getDate(date, "MM")
				+ File.separator + DateUtils.getDate(date, "dd");
		String fileName = UUID.randomUUID().toString().replace("-", "");
		return fssConfig.getDiskPath() + File.separator + dateDir + File.separator + fileName + "." + suffix;
	}

	@Override
	public FSSObject upload(FSSObject fssObject) {
		String filePath = getFullFilePath(fssObject.getSuffix());
		try {
			FileUtils.writeByteArrayToFile(new File(filePath), fssObject.getObjectContent());
			fssObject.setStorage1(filePath);
		} catch (IOException e) {
			throw new ChuangkeException(e);
		}

		fssObject.setStorageType(StorageType.disk.name());
		return fssObject;
	}

	@Override
	public FSSObject download(FSSObject fssObject) {
		File file = new File(fssObject.getStorage1());
		try {
			fssObject.setObjectContent(FileUtils.readFileToByteArray(file));
		} catch (IOException e) {
			throw new ChuangkeException(e);
		}
		return fssObject;
	}

	@Override
	public void delete(FSSObject fssObject) {
		File file = new File(fssObject.getStorage1());
		FileUtils.deleteQuietly(file);
	}

	@Override
	public FileBrief uploadAppenderFile(FileBrief fileBrief) {
		String tmpDir = fssConfig.getTmpDir() + File.separator + fileBrief.getFileMd5();
		try {
			FileUtils.forceMkdir(new File(tmpDir));
		} catch (IOException e) {
			e.printStackTrace();
		}
		fileBrief.setStoreage1(tmpDir);

		return fileBrief;
	}

	@Override
	public boolean appenderFile(FileChunk fileChunk) {
		try {
			String file = fileChunk.getStoreage1() + File.separator + fileChunk.getFilename() + "-"
					+ fileChunk.getChunkNumber();
			FileUtils.writeByteArrayToFile(new File(file), fileChunk.getFile().getBytes());
		} catch (IOException e) {
			throw new ChuangkeException(e);
		}

		return true;
	}

	@Override
	public boolean mergeFile(FileBrief fileBrief) {
		String filename = fileBrief.getFilename();
		String file = getFullFilePath(fileBrief.getSuffix());
		String folder = fileBrief.getStoreage1();
		FileUtils.merge(file, folder, filename);
		return true;
	}

}
